package com.jzo2o.customer.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.jzo2o.api.publics.SmsCodeApi;
import com.jzo2o.common.constants.UserType;
import com.jzo2o.common.enums.SmsBussinessTypeEnum;
import com.jzo2o.common.expcetions.BadRequestException;
import com.jzo2o.common.utils.StringUtils;
import com.jzo2o.customer.model.domain.ServeProvider;
import com.jzo2o.customer.model.dto.request.InstitutionRegisterReqDTO;
import com.jzo2o.customer.service.IServeProviderService;
import com.jzo2o.customer.service.RestPasswordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class RestPasswordServiceImpl implements RestPasswordService {

    @Autowired
    private SmsCodeApi smsCodeApi;

    @Autowired
    private IServeProviderService serveProviderService;

    /**
     * 重置密码
     * @param institutionRegisterReqDTO
     * @return
     */
    @Override
    public void restPassword(InstitutionRegisterReqDTO institutionRegisterReqDTO) {
        // 数据校验
        if(StringUtils.isEmpty(institutionRegisterReqDTO.getVerifyCode())){
            throw new BadRequestException("验证码错误，请重新获取");
        }
        //远程调用publics服务校验验证码是否正确
        boolean verifyResult = smsCodeApi.verify(institutionRegisterReqDTO.getPhone(), SmsBussinessTypeEnum.INSTITUTION_RESET_PASSWORD, institutionRegisterReqDTO.getVerifyCode()).getIsSuccess();
        if(!verifyResult) {
            throw new BadRequestException("验证码错误，请重新获取");
        }
        ServeProvider byId = serveProviderService.findByPhoneAndType(institutionRegisterReqDTO.getPhone(), UserType.INSTITUTION);
        // 密码加密
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode(institutionRegisterReqDTO.getPassword());

        if (ObjectUtil.isEmpty(byId)){
            throw new BadRequestException("手机号未注册！！");
        }else if (byId.getPassword().equals(encode)){
            throw new BadRequestException("密码重复！！");
        } else {
            serveProviderService.update(Wrappers.<ServeProvider>lambdaUpdate().eq(ServeProvider::getId,byId.getId()).set(ServeProvider::getPassword,encode));
        }
    }
}
